//
//  XPStatusesCellViewModel.swift
//  SinaWeibo
//
//  Created by 徐攀 on 16/5/13.
//  Copyright © 2016年 徐攀. All rights reserved.
//

import UIKit

class XPStatusesCellViewModel: NSObject {
    /// 数据模型
    var statuses: XPStatuses?
    
    /// 转发量
    var repostsCount: String?
    /// 评论量
    var commentCount: String?
    /// 赞数
    var attitudesCount: String?
    /// 微博来源
    var source: String?
    /// 配图
    var retweetPicCount: Int = 0
    var originalPicCount: Int = 0
    /// 微博创建时间
    var createTime: String? {
        return NSDate.handleCreatTime(statuses!.created_at ?? "").displayTime
    }
    /// 会员等级图片
    var mBrank: UIImage?
    /// 认证等级图片
    var verifImage: UIImage?
    
    init(statuses: XPStatuses) {
        super.init()
        self.statuses = statuses
        
        repostsCount = handleCount(statuses.reposts_count, defaultTitle: "转发")
        commentCount = handleCount(statuses.comments_count, defaultTitle: "评论")
        attitudesCount = handleCount(statuses.attitudes_count, defaultTitle: "赞")
        
        originalPicCount = statuses.pic_urls?.count ?? 0
        retweetPicCount = statuses.retweeted_status?.pic_urls?.count ?? 0
        
        handleSource(statuses.source)
        mBrank = handleMbrankImage(statuses.user?.mbrank ?? 0)
        
        handleVerifyTypen(statuses.user?.verified_type ?? 0)
     }
    
    // MARK: - 截取微博来源
    private func handleSource(source: String?) {
        guard let sourceFrom = source else {
            return
        }
        if sourceFrom.containsString(">") {
            let rangeStart = sourceFrom.rangeOfString(">")?.endIndex
            let rangeEnd = sourceFrom.rangeOfString("</")?.startIndex
            self.source = sourceFrom.substringWithRange(rangeStart!..<rangeEnd!)
        }
    }
    
    // MARK: - 处理转发数据
    private func handleCount(count: Int, defaultTitle: String) -> String {
        if count > 0 {
            if count >= 10000 {
                return "\(CGFloat(count) / 1000 / 10)万"
            }else {
                return "\(count)"
            }
        }else {
            return defaultTitle
        }
    }

    // MARK: - 处理微博等级
    private func handleMbrankImage(level: Int) -> UIImage? {
        if level > 0 && level < 6 {
            return UIImage(named: "common_icon_membership_level\(level)")
        }else {
            return nil
        }
    }
    
    // MARK: - 处理认证等级
    private func handleVerifyTypen(verify: Int) {
        
        var imageName: String?
        switch verify {
               //  认证类型 -1 没有认证 ，0 认证用户，2，3，5 企业认证 ， 220 达人
        case -1:
            imageName = nil
        case 0:
            imageName = "avatar_vip"
        case 2, 3, 5:
            imageName = "avatar_enterprise_vip"
        case 220:
            imageName = "avatar_grassroot"
        default:
            break
        }
        guard let img = imageName else {
            return
        }
        verifImage = UIImage(named: img)
    }
}
